package com.sample.generator.config.impl;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import com.sample.generator.config.WriterConfig;
import com.sample.generator.io.FileOutputStreamProvider;
import com.sample.generator.io.OutputStreamProvider;
import com.sample.generator.util.GeneratorUtil;

public class FileWriterConfig implements WriterConfig {

	public static final String FILE_ENCODING = "file_encoding";

	private String path;

	private String encoding;

	public FileWriterConfig(String path) {

		this(path, GeneratorUtil.getSystemDefaultEncoding());
	}

	public FileWriterConfig(String path, String encoding) {

		if (path == null) {
			throw new IllegalArgumentException("Argument path is null.");
		}
		if (encoding == null) {
			throw new IllegalArgumentException("Argument encoding is null.");
		}
		this.path = path;
		this.encoding = encoding;
	}

	public String getPath() {

		return path;
	}

	public String getEncoding() {

		return encoding;
	}

	public Writer getWriter() throws IOException {

		OutputStreamProvider provider = new FileOutputStreamProvider();
		OutputStream os = provider.open(path);
		OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
		return new BufferedWriter(osw);
	}

	public Map<String, Object> getContextAttributeMap() {

		Map<String, Object> contextAttributeMap = new HashMap<String, Object>();
		contextAttributeMap.put(FileWriterConfig.FILE_ENCODING, getEncoding());
		return contextAttributeMap;
	}
}
